package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.ActualOrderMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ActualOrderMapper actualOrderMapper;


    @Override
    public ApiResponse userLogin(LoginUser user) {
        try {
            User userResult = userMapper.findUserByUserIDAndPassword(user.getUserID(), user.getPassword());
            //System.out.println(userResult);
            if (userResult != null) {
                String res = JwtUtil.sign(userResult.getUsername(), userResult.getUserID(), "user");
                //System.out.println(res);
                return new ApiResponse(200, "登录成功", res);
            }
            return new ApiResponse(401, "账号或密码出错", null);
        } catch (RuntimeException e) {
            //System.out.println(e);
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public synchronized ApiResponse userRegister(User user) {
        try {
            if (user.getUsername() == null || user.getUsername().trim().isEmpty() ||
                    user.getPassword() == null || user.getPassword().trim().isEmpty() ||
                    user.getUserID() == null || user.getUserID().trim().isEmpty()) {
                return new ApiResponse(400, "输入不能为空", null);
            }

            User existingUser = userMapper.selectOne(new QueryWrapper<User>().eq("userID", user.getUserID()));
            if (existingUser != null) {
                return new ApiResponse(409, "用户ID已存在", null);
            }

            java.util.Date currentDate = new java.util.Date();
            java.sql.Date sqlDate = new java.sql.Date(currentDate.getTime());
            user.setRegistrationDate(sqlDate);

            int result = userMapper.insert(user);
            if (result > 0) {
                return new ApiResponse(200, "注册成功", null);
            }
            return new ApiResponse(500, "注册失败", null);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public ApiResponse getUserInfo(String token) {
        try {
            String userId = JwtUtil.getId(token);
            User user = userMapper.selectById(userId);

            if (user != null) {
                return new ApiResponse(200, "获取成功", user);
            } else {
                return new ApiResponse(404, "用户不存在", null);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public synchronized ApiResponse updateUserInfo(String token, User updatedUser) {
        try {
            String userId = JwtUtil.getId(token);

            if (updatedUser.getUsername() == null || updatedUser.getUsername().trim().isEmpty() ||
                    updatedUser.getPassword() == null || updatedUser.getPassword().trim().isEmpty()) {
                return new ApiResponse(400, "输入不能为空", null);
            }

            User user = userMapper.selectById(userId);
            if (user != null) {
                updatedUser.setUserID(userId);
                updatedUser.setRegistrationDate(user.getRegistrationDate());
                userMapper.updateById(updatedUser);
                return new ApiResponse(200, "更新成功", null);
            }
            return new ApiResponse(404, "用户不存在", null);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public ApiResponse getUserOrders(String token) {
        try {
            String userId = JwtUtil.getId(token);
            List<ActualOrder> orders = actualOrderMapper.selectByUserId(userId);

            if (orders != null && !orders.isEmpty()) {
                return new ApiResponse(200, "订单信息获取成功", orders);
            } else {
                return new ApiResponse(404, "没有找到该用户的订单信息", null);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isInvalidInput(String... inputs) {
        for (String input : inputs) {
            if (input == null || input.trim().isEmpty()) {
                return true;
            }
        }
        return false;
    }
}
